<!--
* @FileDescription: 角色分配菜单
* @Author: zhangjing
* @Date: 2021-9-28 3:27:32 ?F10: PM?
* @LastEditors: zhangjing
* @LastEditTime: 2021-9-28 3:27:32 ?F10: PM?
 -->
<template>
	<globalModal :visible="visible" :confirmLoading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
		<div slot="title">
			分配
			<span style="color: #f00;">({{ (mdl && mdl.roleName) || '' }})</span>
			的菜单权限
		</div>
		<template slot="footer">
			<div class="footer flex flex-pack-justify">
				<a-space :size="8">
					<a-checkbox v-model="isExpand" @change="onCheckExpand">展开/折叠</a-checkbox>
					<a-checkbox v-model="isCheckAll" @change="onCheckAll">全选/全不选</a-checkbox>
				</a-space>
				<div>
					<a-button key="back" @click="handleCancel">取消</a-button>
					<a-button key="submit" type="primary" :loading="confirmLoading" @click="handleOk">确定</a-button>
				</div>
			</div>
		</template>
		<a-spin :spinning="confirmLoading" style="min-height: 450px;">
			<a-tabs default-active-key="1">
				<a-tab-pane key="1" tab="管理平台端菜单">
					<a-tree
						checkable
						@check="onCheck"
						:checkedKeys="checkedKeys"
						:treeData="treeData"
						@expand="onExpand"
						:expandedKeys="expandedKeys"
						:checkStrictly="checkStrictly"
						:replaceFields="replaceFields"
					></a-tree>
				</a-tab-pane>
				<!-- <a-tab-pane key="2" tab="小程序菜单">
					<a-tree
						checkable
						@check="onminiCheck"
						:checkedKeys="minicheckedKeys"
						:treeData="minitreeData"
						@expand="onminiExpand"
						:expandedKeys="miniexpandedKeys"
						:checkStrictly="checkStrictly"
						:replaceFields="replaceFields"
					></a-tree>
				</a-tab-pane> -->
			</a-tabs>
		</a-spin>
	</globalModal>
</template>

<script>
import { sysManageapi } from '@/api/index.js';
import { ModalMixins } from '@/mixins';
import { clearDeep } from '@/utils/base';
export default {
	name: 'roleJoinMenuModal',
	data() {
		return {
			roleId: '',
			title: '分配菜单权限',
			treeData: [],
			checkedKeys: [],
			expandedKeys: [],
			allTreeKeys: [],
			autoExpandParent: true,
			checkStrictly: true, //默认父子关联
			isExpand: true,
			isCheckAll: false,
			minitreeData: [],
			minicheckedKeys: [],
			miniexpandedKeys: [],
			miniallTreeKeys: [],
			replaceFields: { children: 'children', title: 'name', key: 'menuId', value: 'menuId' }
		};
	},
	mixins: [ModalMixins],
	created() {},
	methods: {
		show(record) {
			this.mdl = Object.assign({}, { dataScope: 1, deptIds: [] }, record);
			this.visible = true;
			this.roleId = record.roleId;
			this.treeData = [];
			this.minitreeData = [];
			let PromiseList = [];
			PromiseList.push(this.getMenuTree());
			//PromiseList.push(this.getMiniMenuTree());
			PromiseList.push(this.roleJoinMenu());
			this.confirmLoading = true;
			Promise.all(PromiseList)
				.then(result => {
					// console.log(result); //['成功了', 'success']
				})
				.finally(() => {
					this.confirmLoading = false;
				});
		},
		handleOk() {
			/* 过滤一次不在数组中的 key */
			if (this.checkedKeys && this.checkedKeys.length > 0) {
				this.checkedKeys = this.checkedKeys.filter(item => this.allTreeKeys.includes(item));
			}
			if (this.minicheckedKeys && this.minicheckedKeys.length > 0) {
				this.minicheckedKeys = this.minicheckedKeys.filter(item => this.miniallTreeKeys.includes(item)).map(item => item + '');
			}
			console.log('哈哈哈', this.checkedKeys);
			// return false;
			this.confirmLoading = true;
			this.$postAction(sysManageapi.roleUrl.setRoleMenu, {
				roleId: this.roleId,
				menuIds: [...this.checkedKeys, ...this.minicheckedKeys]
			})
				.then(res => {
					if (res && res.code == 1) {
						this.$message.success('保存成功');
						this.$emit('ok');
						this.handleCancel();
					}
				})
				.finally(() => {
					this.confirmLoading = false;
				});
		},
		handleCancel() {
			this.reset();
			this.$emit('close');
			this.visible = false;
		},
		getMenuTree() {
			return this.$postAction(sysManageapi.menuUrl.getList, {
				orgId: this.orgId
			}).then(res => {
				if (res && res.code == 1) {
					this.treeData = res.data;
					let list = JSON.stringify(this.treeData)
						.match(/(?=\"menuId\":)([^,]*)(?=\,)/g)
						.join(',')
						.replace(/"menuId":/g, '')
						.replace(/\"/g, '')
						.split(',');
					this.allTreeKeys = list.map(item => item);
					this.expandedKeys = [...this.allTreeKeys];
				}
			});
		},
		getMiniMenuTree() {
			return this.$postAction(sysManageapi.minimenuUrl.getList, {
				roleId: this.roleId
			}).then(res => {
				if (res && res.code == 1) {
					this.minitreeData = res.data;
					let list = JSON.stringify(this.minitreeData)
						.match(/(?=\"menuId\":)([^,]*)(?=\,)/g)
						.join(',')
						.replace(/"menuId":/g, '')
						.replace(/\"/g, '')
						.split(',');
					this.miniallTreeKeys = list.map(item => item);
					this.miniexpandedKeys = [...this.miniallTreeKeys];
				}
			});
		},
		/* 查询角色关联菜单数据回填 */
		roleJoinMenu() {
			return this.$postAction(sysManageapi.roleUrl.roleByMenu + '?roleId=' + this.roleId).then(res => {
				if (res && res.code == 1) {
					this.checkedKeys = res.data.pcMenuIds || [];
					this.minicheckedKeys = res.data.wcMenuIds || [];
				}
			});
		},
		treeFindPath(tree, func, path = []) {
			if (!tree) return [];
			for (const data of tree) {
				// 这里按照你的需求来存放最后返回的内容吧
				path.push(data.menuId);
				if (func(data)) return path;
				if (data.children) {
					const findChildren = this.treeFindPath(data.children, func, path);
					if (findChildren.length) return findChildren;
				}
				path.pop();
			}
			return [];
		},
		onCheck(o, e) {
			if (this.checkStrictly) {
				this.checkedKeys = o.checked;
			} else {
				this.checkedKeys = o;
			}
			/* 关联子集 */
			let childKeys = JSON.stringify(e.node.dataRef)
				.match(/(?=\"menuId\":)([^,]*)(?=\,)/g)
				.join(',')
				.replace(/"menuId":/g, '')
				.replace(/\"/g, '');
			if (childKeys.length > 0) {
				childKeys = childKeys.split(',');
			}
			childKeys = childKeys.map(id => id);
			if (e.checked) {
				this.checkedKeys = this.checkedKeys.concat(childKeys);
				/* 关联父级 */
				let parentkey = this.treeFindPath(this.treeData, data => data.menuId === e.node.dataRef.menuId);
				// console.log('fuji', parentkey)
				this.checkedKeys = this.checkedKeys.concat(parentkey);
			} else {
				let keys = [];
				for (var i = 0; i < this.checkedKeys.length; i++) {
					if (!childKeys.some(item => item == this.checkedKeys[i])) {
						keys.push(this.checkedKeys[i]);
					}
				}
				this.checkedKeys = keys;
			}
			/* 数组去重 */
			this.checkedKeys = Array.from(new Set(this.checkedKeys));
		},
		onminiCheck(o, e) {
			if (this.checkStrictly) {
				this.minicheckedKeys = o.checked;
			} else {
				this.minicheckedKeys = o;
			}
			/* 关联子集 */
			let childKeys = JSON.stringify(e.node.dataRef)
				.match(/(?=\"menuId\":)([^,]*)(?=\,)/g)
				.join(',')
				.replace(/"menuId":/g, '')
				.replace(/\"/g, '');
			if (childKeys.length > 0) {
				childKeys = childKeys.split(',');
			}
			childKeys = childKeys.map(id => id);
			if (e.checked) {
				this.minicheckedKeys = this.minicheckedKeys.concat(childKeys);
				/* 关联父级 */
				let parentkey = this.treeFindPath(this.minitreeData, data => data.menuId === e.node.dataRef.menuId);
				// console.log('fuji', parentkey)
				this.minicheckedKeys = this.minicheckedKeys.concat(parentkey);
			} else {
				let keys = [];
				for (var i = 0; i < this.minicheckedKeys.length; i++) {
					if (!childKeys.some(item => item == this.minicheckedKeys[i])) {
						keys.push(this.minicheckedKeys[i]);
					}
				}
				this.minicheckedKeys = keys;
			}
			/* 数组去重 */
			this.minicheckedKeys = Array.from(new Set(this.minicheckedKeys));
		},
		onExpand(expandedKeys) {
			this.expandedKeys = expandedKeys;
			this.autoExpandParent = false;
		},
		onminiExpand(expandedKeys) {
			this.miniexpandedKeys = expandedKeys;
			this.autoExpandParent = false;
		},
		reset() {
			this.expandedKeys = [];
			this.checkedKeys = [];
			this.autoExpandParent = true;
			this.checkStrictly = true; //默认父子关联
			this.isExpand = true;
			this.isCheckAll = false;
			this.confirmLoading = false;
		},
		expandAll() {
			this.expandedKeys = [...this.allTreeKeys];
			this.miniexpandedKeys = [...this.miniallTreeKeys];
		},
		closeAll() {
			this.expandedKeys = [];
			this.miniexpandedKeys = [];
		},
		checkALL() {
			this.checkedKeys = [...this.allTreeKeys];
			this.minicheckedKeys = [...this.miniallTreeKeys];
		},
		cancelCheckALL() {
			this.checkedKeys = [];
			this.minicheckedKeys = [];
		},
		/* 切换展开/折叠 */
		onCheckExpand(e) {
			this.isExpand = e.target.checked;
			if (e.target.checked) {
				this.expandAll();
			} else {
				this.closeAll();
			}
		},
		/* 切换全选 */
		onCheckAll(e) {
			this.isCheckAll = e.target.checked;
			if (e.target.checked) {
				this.checkALL();
			} else {
				this.cancelCheckALL();
			}
		}
	}
};
</script>

<style scoped lang="less">
	.footer{
		padding:0 20px;
	}
</style>
